/* model */
import { RoleAuth, RoleAuthGroup, RoleTwoAuthGroup } from "@model/entity/Role/Role"
import { AuthTreeNode } from '@src/modules/account/roleService/component/AuthTree/model'
/* util */
import { isArray, isNotArray, isNotEmpty } from '@src/util/type'

const DefaultRoleViewMinWidth = 1240

function getDefaultCheckedKeys(authGroups: RoleAuthGroup[]) {
  
  // 默认树节点选中的 keys
  let defaultCheckedKeys: string[] = []
  
  authGroups.forEach(authGroup => {
    getAuthGroupCheckedKeys(authGroup, defaultCheckedKeys)
  })
  
  return defaultCheckedKeys
}

function getAuthGroupCheckedKeys(authGroup: RoleAuthGroup, keys: string[]) {
  
  if (isNotArray(authGroup?.twoAuthorityGroupList)) {
    return
  }
  
  authGroup.twoAuthorityGroupList.forEach((group: RoleTwoAuthGroup) => {
    
    if (isArray(group?.authorityList)) {
        
        group.authorityList.forEach((auth: RoleAuth) => {
          
          if (auth.check) {
            keys.push(auth.enName.toString())
          }
          
        })
        
    }
    
  })
  
}

function getDefaultExpandedKeys(authGroups: RoleAuthGroup[]) {
  
  const expandedKeys: string[] = []
  
  authGroups.forEach(authGroup => {
    authGroup.twoAuthorityGroupList.forEach(group => {
      expandedKeys.push(group.twoGroupId)
    })
  })
  
  return expandedKeys
}

function getChildrenKeysByParentKey(key: string, tree: AuthTreeNode[]) {
  
  const childrenKeys: string[] = []
  
  tree.forEach(node => {
    getParentChildrenKeys(key, node, childrenKeys)
  })
  
  return childrenKeys
}


function getParentChildrenKeys(key: string, node: AuthTreeNode, keys: string[]) {
  
  if (isNotEmpty(keys)) {
    return
  }
  
  if (isNotArray(node?.children)) {
    return
  }
  
  const childrenKeys = node.children.map(child => child.key)
  
  if (childrenKeys.includes(key)) {
    keys.push(...childrenKeys)
    return
  }
  
  node.children.forEach(child => {
    getParentChildrenKeys(key, child, keys)
  })
}

function getWaterfallItemWidth(col: number = 2) {
  
  let clientWidth = document.body.clientWidth
  
  clientWidth = clientWidth > DefaultRoleViewMinWidth ? clientWidth : DefaultRoleViewMinWidth
  
  const otherWidth = 296
  const roleTreeWidth = clientWidth - otherWidth
  
  return roleTreeWidth / col
}

export {
  getDefaultCheckedKeys,
  getChildrenKeysByParentKey,
  getWaterfallItemWidth,
  getDefaultExpandedKeys
}

export default {
  getDefaultCheckedKeys,
  getChildrenKeysByParentKey,
  getWaterfallItemWidth,
  getDefaultExpandedKeys
}